package com.aaa.service.impl;

import com.aaa.dao.PermissionMapper;
import com.aaa.dao.UserMapper;
import com.aaa.entity.MyUser;
import com.aaa.entity.Permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (MyUser)表服务接口
 *
 * @author makejava
 * @since 2023-01-03 09:52:32
 */
@Service
public class UserService implements UserDetailsService {
    @Resource
    private PermissionMapper permissionDao;

    @Resource
    private UserMapper userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

//        LambdaQueryWrapper<MyUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(MyUser::getUsername,username);
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        MyUser myUser = userDao.selectOne(queryWrapper);

        if(myUser != null){
            List<Permission> permissions = permissionDao.selectPermissionByUserid(myUser.getUserid());
            /**
             * 返回UserDetails对象---它是一个接口，返回它的实现类。
             * String username,账户
             * String password,密码数据库中的密码
             * 	Collection<? extends GrantedAuthority> authorities: 该用户具有的权限
             */
            List<SimpleGrantedAuthority> authorities= permissions.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            return new User(username, myUser.getUserpwd(), authorities);
        }
        return null;
    }
}

